#include "fault_unbalance.hpp"

using namespace motion;

void fault_unbalance::mTicked(void)
{
	if(WarningEnable)
	{
		if(FaultStatus == FAULT_STATUS_HAPPEND || FaultStatus == FAULT_STATUS_RESUME)
		{
			WarningStatus = true;
		}
		else
		{
			if(!CompareValue(false))
			{
				WarningStatus = false;
				mWarningCount = 0;
			}
			else if(mWarningCount < WarningTrigTime)
			{
				mWarningCount++;
				if(mWarningCount >= WarningTrigTime)
				{
					WarningStatus = true;
				}
			}
		}
	}
	else
	{
		WarningStatus = false;
	}
	if(!FaultEnable)
	{
		return;
	}
	switch(FaultStatus)
	{
		case FAULT_STATUS_NONE:
			if(CompareValue(false))
			{
				FaultStatus = FAULT_STATUS_HOLD;
			}
			if(mTrigTimeCount)
			{
				mTrigTimeCount--;
			}
			if(mDamageTrigTimeCount)
			{
				mDamageTrigTimeCount--;
			}
			break;
		case FAULT_STATUS_HOLD:
			if(!CompareValue(false))
			{
				FaultStatus = FAULT_STATUS_NONE;
			}
			else if(ResourceValue[0] >= 90 && !IsRunning) ///> 启动过程中故障
			{
				mDamageTrigTimeCount++;
				if(mDamageTrigTimeCount > 700)
				{
					FaultStatus = FAULT_STATUS_HAPPEND;
					mDamageTrigTimeCount = 0;
				}
			}
			else if(mTrigTimeCount < FaultTrigTime)
			{
				mTrigTimeCount++;
				if(mTrigTimeCount >= FaultTrigTime)
				{
					FaultStatus = FAULT_STATUS_HAPPEND;
					mTrigTimeCount = 0;
					uint8_t i;
					for(i = 0; i < ResourceValueLen; i++)
					{
						FreezValue[i] = ResourceValue[i];
					}
				}
			}
			break;
		case FAULT_STATUS_HAPPEND:
			if(CompareValue(true))
			{
				FaultStatus = FAULT_STATUS_RESUME;
			}
			if(mResumeTimeCount)
			{
				mResumeTimeCount--;
			}
			break;
		case FAULT_STATUS_RESUME:
			if(!CompareValue(true))
			{
				FaultStatus = FAULT_STATUS_HAPPEND;
			}
			else if(mResumeTimeCount < FaultResumeTime)
			{
				mResumeTimeCount++;
				if(mResumeTimeCount >= FaultResumeTime)
				{
					FaultStatus = FAULT_STATUS_NONE;
					mResumeTimeCount = 0;
				}
			}
			break;
	}
}

fault_unbalance::fault_unbalance(void)
	:fault_big()
{
	FaultTrigCompareMethod = FAULT_COMPAREMETHOD_OR;
	FaultResumeCompareMethod = FAULT_COMPAREMETHOD_AND;
	mDamageTrigTimeCount = 0;
	ResourceValueLen = 1;
	IsRunning = false;
}

fault_unbalance::~fault_unbalance(void)
{
	Unregister();
}
